<?php
/**
 * 如花拼团开源系统 -- 永久免费
 * =========================================================
 * 官方网址：http://www.phps.shop
 * 作者：光爵【API + 后台】 、 小草【小程序 + WAP】
 * QQ 交流群：728615087
 * Version：1.0.0
 */
namespace app\api\model;


use app\lib\exception\BaseException;
use app\lib\exception\SuccessMessage;
use think\Db;

class Article extends BaseModel
{
    protected $hidden = ['is_hidden','author','create_time','update_time','delete_time'];

    //文章关联多个分类
    public function categoryContent()
    {
        return $this->hasMany('ArticleType','article_id','id');
    }

    //文章关联单个分类
    public function categoryContentOne()
    {
        return $this->hasOne('ArticleType','article_id','id');
    }

    //创建用户行程安排
    public static function CreateOne($post)
    {
        $Article = new Article;
        $Article_type = new ArticleType();
        Db::startTrans();
        try {
            $res = (empty($post['id'])) ? false : true;
            $Article->isUpdate($res)->save($post); //直接通过关联模型来新增
            $data['article_id'] = empty($post['id']) ? $Article->id : $post['id'] ;
            foreach ($post['category_content'] as $key => $value){
                $data['content'] = $value['content'];
                if(!empty($value['id'])){//有二级分类时
                    $data['id'] = $value['id'];
                    $Article_type->isUpdate(true)->update($data);
                }else{
                    $data['category_id'] = $post['type'];
                    $Article_type->save($data);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();// 回滚事务
            throw new BaseException(['msg' => '新增行程安排失败']);
        }
        return json(new SuccessMessage(), 201);
    }

    //获取所有文章，包含分页
    public static function getarticleByPage($page=1, $size=10,$key='',$where=''){
        if(!empty($key)){
            $data = self::where($where)->where('title','like','%'.$key.'%')
                ->order('create_time desc')->paginate($size,'',['page' => $page]);
        }else{
            $data = self::where($where)->order('create_time desc')
                ->paginate($size,'',['page' => $page]);
        }
        return $data;
    }
}